package com.dangdang.sharding.listener.spring.core;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.context.ApplicationContext;

import com.dangdang.sharding.listener.event.Event;
import com.dangdang.sharding.listener.event.EventListener;
import com.dangdang.sharding.listener.source.ApplicationEventPublisher;

public class CglibProxyFactory implements MethodInterceptor {
    private ApplicationEventPublisher target;
    private ApplicationContext applicationContext;
    
    public CglibProxyFactory(ApplicationEventPublisher target, ApplicationContext applicationContext) {
		super();
		this.target = target;
		this.applicationContext = applicationContext;
	}
    

	private void addListeners(ApplicationEventPublisher publisher,Class<?> eventClass) {
		String[] beans = applicationContext.getBeanNamesForType(EventListener.class);
		for (String name : beans) {
			@SuppressWarnings("unchecked")
			EventListener<Event> eventListener = (EventListener<Event>) applicationContext.getBean(name);
			Type[] types = eventListener.getClass().getGenericInterfaces();
			ParameterizedType parameterizedType = (ParameterizedType) types[0];
			Type type = parameterizedType.getActualTypeArguments()[0];
			if(eventClass.getName().equals(type.getTypeName())) {
				target.addListener(eventListener);
			}
		}
	}

	
	public Object getProxyInstance() {
        // 创建 Enhancer 对象
        Enhancer enhancer = new Enhancer();
        // 设置目标对象的Class
        enhancer.setSuperclass(target.getClass());
        // 设置回调操作，相当于InvocationHandler
        enhancer.setCallback(this);
        return enhancer.create();
    }
    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)
            throws Throwable {
        addListeners(target,args[0].getClass());
        Object invoke = method.invoke(target, args);
        return invoke;
    }
}